#!/usr/bin/ python3
import os
# git module 安装命令:pip3 install gitpython
from git import Repo
import subprocess
import shutil
import re
import logging as log


# 默认输出内容格式如：b'[INFO] Finished at: 2020-12-30T16:29:23+08:00'
# str_resolve()函数作用是提取单引号「]'」之间的内容
def str_resolve(st):
    pattern = re.compile("](.*)'")
    return pattern.findall(str(st))[0]


def mvn_archetype():
    # 执行maven命令
    log.info("--->>> mvn archetype:create-from-project <<<---")
    archetype = subprocess.Popen("mvn archetype:create-from-project", shell=True, stdout=subprocess.PIPE)
    while archetype.poll() is None:
        readline = archetype.stdout.readline()
        readline = readline.strip()
        if readline:
            log.info("{}".format(str_resolve(readline)))

    if archetype.returncode == 0:
        log.info("---<<< 执行成功！>>>---")
        archetype.kill()
    else:
        log.error("「mvn archetype:create-from-project」命令执行错误！")
        raise Exception("「mvn archetype:create-from-project」命令执行错误！")

    os.chdir("target/generated-sources/archetype")


def mvn_install():
    log.info("--->>> mvn install <<<---")
    install = subprocess.Popen("mvn install", shell=True, stdout=subprocess.PIPE, stderr=True)
    while install.poll() is None:
        readline = install.stdout.readline()
        readline = readline.strip()
        if readline:
            log.info("{}".format(str_resolve(readline)))
    if install.returncode == 0:
        log.info("---<<< 执行成功！>>>---")
        install.kill()
    else:
        log.error("「mvn install」命令执行错误！")
        raise Exception("「mvn install」命令执行错误！")


def mvn_archetype_generate(project_dir):
    os.chdir(project_dir)
    os.system("mvn archetype:generate -DarchetypeCatalog=local")


class CreateProject:
    def __init__(self, first, project_dir, git_addr):
        self.first = first
        self.project_dir = project_dir
        self.git_addr = git_addr

        log.basicConfig(format='%(asctime)s - %(levelname)s %(message)s', level=log.INFO)

    def __create_mvn_module_project__(self):
        if self.first == "Y" or self.first == "y":
            self.ready_env()
            # 1、执行命令：mvn archetype:create-from-project
            mvn_archetype()
            # 2、执行命令：mvn install
            mvn_install()

        if not os.path.exists(self.project_dir):
            os.mkdir(self.project_dir)

        # 3、执行命令：mvn archetype:generate -DarchetypeCatalog=local
        mvn_archetype_generate(self.project_dir)

        log.info("到此，您的工程创建成功！您可以切换到目录「{}」中查看！".format(self.project_dir))
        log.info("顺颂商祺！！！")

    def ready_env(self):
        # 获取并切换到用户主目录
        user_home_dir = os.environ["HOME"]
        os.chdir(user_home_dir)

        split = self.git_addr.split("/")
        pro_name = str(split[len(split) - 1]).split(".")[0]

        # 创建工程模板下载保存路径
        if os.path.exists(pro_name):
            shutil.rmtree(pro_name, ignore_errors=True)

        os.mkdir(pro_name)

        # 切换到{pro_name}目录下
        os.chdir(pro_name)

        # git clone到当前目录
        Repo.clone_from(self.git_addr, os.getcwd())
